package com.lingo.a2b.common.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lingo.a2b.common.handler.ValueConvertHandler;
import com.lingo.a2b.model.entity.ValueConvert;
import com.lingo.a2b.service.ValueConvertService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author lingo
 * @version v1.0
 * @date 2020/9/2 12:00
 * @Company www.xyb2b.com
 */
@Component
@Slf4j
public class AutoCollectValueConvertHandler implements ApplicationRunner {

    @Autowired
    private ValueConvertService valueConvertService;
    @Autowired
    private ApplicationContext applicationContext;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void run(ApplicationArguments args) throws Exception {
        try{
            LambdaQueryWrapper<ValueConvert> wrapper = new QueryWrapper<ValueConvert>().lambda().isNotNull(ValueConvert::getFid);
            valueConvertService.remove(wrapper);
            Map<String, ValueConvertHandler> beansOfType = applicationContext.getBeansOfType(ValueConvertHandler.class);
            if (CollectionUtils.isEmpty(beansOfType)){
                return;
            }
            List<ValueConvert> container = new ArrayList<>(beansOfType.size());
            beansOfType.forEach((key, value) -> {
                ValueConvert valueConvert = new ValueConvert();
                String className = value.getClass().getName();
                valueConvert.setFprojectId(value.belongTo());
                valueConvert.setFhandlerClass(className);
                valueConvert.setFname(className);
                valueConvert.setFisTemp(false);
                container.add(valueConvert);
            });
            valueConvertService.saveBatch(container);
        }catch (Exception e){
            log.error("ValueConvertHandler Initiation Failed!");
            throw e;
        }
        log.info("ValueConvertHandler Initiation Finished!");
    }
}
